package com.xmb.wechat.view.wechat.money;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.nil.sdk.utils.DateUtils;
import com.squareup.picasso.Picasso;
import com.xmb.wechat.R;
import com.xmb.wechat.R2;
import com.xmb.wechat.application.WechatStartApplication;
import com.xmb.wechat.base.BaseActivity;
import com.xmb.wechat.bean.BankCardBean;
import com.xmb.wechat.bean.TradeHistoryBean;
import com.xmb.wechat.bean.WechatContactBean;
import com.xmb.wechat.common.Constant;
import com.xmb.wechat.definterface.PicChooseWithOutCutCallBack;
import com.xmb.wechat.definterface.SimpleTextWatcher;
import com.xmb.wechat.util.PicChooseUtils;
import com.xmb.wechat.util.PicLoadUtils;
import com.xmb.wechat.widget.TitleLayout;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @Author lijiangop
 * @CreateTime 2020/4/22 17:52
 */
public class WechatFundTradeHistoryAddActivity extends BaseActivity {

    private static final int REQUEST_CODE_BANK_CARD = 103;

    @BindView(R2.id.title_layout)
    TitleLayout  mTitleLayout;
    @BindView(R2.id.iv_type)
    ImageView    mIvType;
    @BindView(R2.id.tv_type)
    TextView     mTvType;
    @BindView(R2.id.ll_content)
    LinearLayout mLlContent;
    @BindView(R2.id.et_type)
    EditText     mEtType;
    @BindView(R2.id.tv_expend)
    TextView     mTvExpend;
    @BindView(R2.id.tv_income)
    TextView     mTvIncome;
    @BindView(R2.id.tv_trade_time)
    TextView     mTvTradeTime;
    @BindView(R2.id.ll_trade_time)
    LinearLayout mLlTradeTime;
    @BindView(R2.id.et_money)
    EditText     mEtMoney;

    private TradeHistoryBean mTradeHistoryEntity;
    private int              mType;

    public WechatFundTradeHistoryAddActivity() {
        super(R.layout.activity_fund_trade_history_add);
    }

    public static void start(Activity activity, int type, int requestCode) {
        Intent intent = new Intent(activity, WechatFundTradeHistoryAddActivity.class);
        intent.putExtra("type", type);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void initView() {
        mType = getIntent().getIntExtra("type", Constant.TradeHistoryType.TYPE_ZIDINGYI);
        mTradeHistoryEntity = new TradeHistoryBean();
        mTitleLayout.setRightClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TradeHistoryBean tradeHistoryEntity = checkValueAvaliable();
                if (tradeHistoryEntity == null)
                    return;
                setResult(RESULT_OK, new Intent());
                WechatStartApplication.getBoxStore().boxFor(TradeHistoryBean.class).put(tradeHistoryEntity);
                WechatFundTradeHistoryAddActivity.this.finish();
            }
        });
        mEtMoney.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void onTextChangedFinish(String value) {
                if (!TextUtils.isEmpty(value)) {
                    try {
                        double money = Double.parseDouble(value);
                        mTradeHistoryEntity.setMoney(money);
                    } catch (Exception e) {
                        ToastUtils.showShort("金额输入有误");
                        e.printStackTrace();
                    }
                }
            }
        });
        mEtType.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void onTextChangedFinish(String value) {
                mTradeHistoryEntity.setContent(value);
            }
        });
        //init
        setTradeState(true);
        //init
        mTradeHistoryEntity.setType(mType);
        switch (mType) {
            case Constant.TradeHistoryType.TYPE_ZIDINGYI:
                mTvType.setText("自定义");
                mEtType.setHint("请输入商品名称");
                mLlContent.setVisibility(View.VISIBLE);
                mTitleLayout.setTitle("添加自定义记录");
                PicLoadUtils.setupRoundPicIntoImageView(Constant.SourceType.AVATAR_SRC_APP_INNER_DRAWABLE, String.valueOf(R.drawable.img_default_gray), mIvType);
                mTradeHistoryEntity.setIconUrl(String.valueOf(R.drawable.img_default_gray));
                mTradeHistoryEntity.setIconSourceType(Constant.SourceType.AVATAR_SRC_APP_INNER_DRAWABLE);
                break;
            case Constant.TradeHistoryType.TYPE_RED_PACKET:
                mTvType.setText("请选择对象");
                mTvType.setTextColor(getResources().getColor(R.color.black_60));
                mTitleLayout.setTitle("添加红包记录");
                mTvExpend.setText("发送");
                mTvIncome.setText("接收");
                PicLoadUtils.setupRoundPicIntoImageView(Constant.SourceType.AVATAR_SRC_APP_INNER_DRAWABLE, String.valueOf(R.drawable.ic_wx_default_avatar), mIvType);
                break;
            case Constant.TradeHistoryType.TYPE_ZHUANZHANG:
                mTvType.setText("请选择对象");
                mTvType.setTextColor(getResources().getColor(R.color.black_60));
                mTitleLayout.setTitle("添加转账记录");
                mTvExpend.setText("转出");
                mTvIncome.setText("转入");
                PicLoadUtils.setupRoundPicIntoImageView(Constant.SourceType.AVATAR_SRC_APP_INNER_DRAWABLE, String.valueOf(R.drawable.ic_wx_default_avatar), mIvType);
                break;
            case Constant.TradeHistoryType.TYPE_QRCODE:
                mTvType.setText("请选择对象");
                mTvType.setTextColor(getResources().getColor(R.color.black_60));
                mTitleLayout.setTitle("添加二维码收款记录");
                mTvExpend.setText("付款");
                mTvIncome.setText("收款");
                PicLoadUtils.setupRoundPicIntoImageView(Constant.SourceType.AVATAR_SRC_APP_INNER_DRAWABLE, String.valueOf(R.drawable.ic_wx_default_avatar), mIvType);
                break;
            case Constant.TradeHistoryType.TYPE_CHANGE:
                mTvType.setText("请选择银行卡");
                mTvType.setTextColor(getResources().getColor(R.color.black_60));
                mTitleLayout.setTitle("添加零钱交易记录");
                mTvExpend.setText("提现");
                mTvIncome.setText("充值");
                PicLoadUtils.setupRoundPicIntoImageView(Constant.SourceType.AVATAR_SRC_APP_INNER_DRAWABLE, String.valueOf(R.drawable.img_default_gray), mIvType);
                break;
        }
    }

    @OnClick({R2.id.ll_type, R2.id.tv_expend, R2.id.tv_income, R2.id.ll_trade_time})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.ll_type) {
            doTypeChoose();
        } else if (id == R.id.tv_expend) {
            setTradeState(true);
        } else if (id == R.id.tv_income) {
            setTradeState(false);
        } else if (id == R.id.ll_trade_time) {
            KeyboardUtils.hideSoftInput(WechatFundTradeHistoryAddActivity.this);
            showTimeChoose((date, v) -> {
                mTradeHistoryEntity.setTradeTime(date.getTime());
                mTvTradeTime.setText(DateUtils.getStringByFormat(date, "yyyy-MM-dd HH:mm:ss"));
            });
        }
    }

    /**
     * 类型选择
     */
    @SuppressLint("IntentReset")
    private void doTypeChoose() {
        switch (mType) {
            case Constant.TradeHistoryType.TYPE_ZIDINGYI:
                PicChooseUtils.chooseOnePicWithOutCut(WechatFundTradeHistoryAddActivity.this, new PicChooseWithOutCutCallBack() {
                    @Override
                    public void onPicChoose(String... Pic) {
                        if (TextUtils.isEmpty(Pic[0]))
                            return;
                        PicLoadUtils.loadSdcardPic(Pic[0], mIvType);
                        //添加
                        mTradeHistoryEntity.setIconSourceType(Constant.SourceType.AVATAR_SRC_SDCARD);
                        mTradeHistoryEntity.setIconUrl(Pic[0]);
                    }
                });
                break;
            case Constant.TradeHistoryType.TYPE_RED_PACKET:
            case Constant.TradeHistoryType.TYPE_ZHUANZHANG:
            case Constant.TradeHistoryType.TYPE_QRCODE:
                showRoleChooseSender(this, false, false, null);
                break;
            case Constant.TradeHistoryType.TYPE_CHANGE:
                WechatFundBankCardActivity.startforResult(this, REQUEST_CODE_BANK_CARD);
                break;
        }
    }

    /**
     * 设置交易类型
     *
     * @param isExpend 是否是支出
     */
    private void setTradeState(boolean isExpend) {
        mTvExpend.setSelected(isExpend);
        mTvIncome.setSelected(!isExpend);
        mTradeHistoryEntity.setExpend(isExpend);
    }

    /**
     * 选择时间
     *
     * @param listener
     */
    private void showTimeChoose(OnTimeSelectListener listener) {
        @SuppressLint("SimpleDateFormat")
        TimePickerView pvTime = new TimePickerBuilder(this, listener).setType(new boolean[]{true, true, true, true, true, true})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setTitleSize(20)//标题文字大小
                .setTitleText("时间")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setSubmitColor(getResources().getColor(R.color.wechat_tab_bg_green))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.wechat_tab_bg_green))//取消按钮文字颜色
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();
        pvTime.show();
    }

    /**
     * 检查数据是否全部填写选择完毕
     *
     * @return
     */
    private TradeHistoryBean checkValueAvaliable() {
        switch (mType) {
            case Constant.TradeHistoryType.TYPE_ZIDINGYI:
                if (TextUtils.isEmpty(mTradeHistoryEntity.getContent())) {
                    ToastUtils.showShort("请填写交易内容");
                    return null;
                }
                if (mTradeHistoryEntity.getTradeTime() == 0) {
                    ToastUtils.showShort("请选择交易时间");
                    return null;
                }
                if (mTradeHistoryEntity.getMoney() == 0) {
                    ToastUtils.showShort("请填写交易金额");
                    return null;
                }
                break;
            case Constant.TradeHistoryType.TYPE_RED_PACKET:
                if (TextUtils.isEmpty(mTradeHistoryEntity.getContent())) {
                    ToastUtils.showShort("请选择红包对象");
                    return null;
                }
                if (mTradeHistoryEntity.getTradeTime() == 0) {
                    ToastUtils.showShort("请选择交易时间");
                    return null;
                }
                if (mTradeHistoryEntity.getMoney() == 0) {
                    ToastUtils.showShort("请填写交易金额");
                    return null;
                }
                mTradeHistoryEntity.setContent("微信红包-" + (mTradeHistoryEntity.isExpend() ? "发给" : "来自") + mTradeHistoryEntity.getContent());
                break;
            case Constant.TradeHistoryType.TYPE_ZHUANZHANG:
                if (TextUtils.isEmpty(mTradeHistoryEntity.getContent())) {
                    ToastUtils.showShort("请选择转账对象");
                    return null;
                }
                if (mTradeHistoryEntity.getTradeTime() == 0) {
                    ToastUtils.showShort("请选择交易时间");
                    return null;
                }
                if (mTradeHistoryEntity.getMoney() == 0) {
                    ToastUtils.showShort("请填写交易金额");
                    return null;
                }
                mTradeHistoryEntity.setContent("转账-" + (mTradeHistoryEntity.isExpend() ? "转给" : "来自") + mTradeHistoryEntity.getContent());
                break;
            case Constant.TradeHistoryType.TYPE_QRCODE:
                if (TextUtils.isEmpty(mTradeHistoryEntity.getContent())) {
                    ToastUtils.showShort("请选择二维码交易对象");
                    return null;
                }
                if (mTradeHistoryEntity.getTradeTime() == 0) {
                    ToastUtils.showShort("请选择交易时间");
                    return null;
                }
                if (mTradeHistoryEntity.getMoney() == 0) {
                    ToastUtils.showShort("请填写交易金额");
                    return null;
                }
                mTradeHistoryEntity.setContent(mTradeHistoryEntity.isExpend() ? "扫二维码付款-给" + mTradeHistoryEntity.getContent() : "二维码收款-来自" + mTradeHistoryEntity.getContent());
                break;
            case Constant.TradeHistoryType.TYPE_CHANGE:
                if (TextUtils.isEmpty(mTradeHistoryEntity.getContent())) {
                    ToastUtils.showShort("请选择银行卡");
                    return null;
                }
                if (mTradeHistoryEntity.getTradeTime() == 0) {
                    ToastUtils.showShort("请选择交易时间");
                    return null;
                }
                if (mTradeHistoryEntity.getMoney() == 0) {
                    ToastUtils.showShort("请填写交易金额");
                    return null;
                }
                mTradeHistoryEntity.setContent(mTradeHistoryEntity.isExpend() ? "零钱提现-到" + mTradeHistoryEntity.getContent() : "零钱充值-来自" + mTradeHistoryEntity.getContent());
                break;
        }
        return mTradeHistoryEntity;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null)
            return;
        switch (requestCode) {
            case REQUEST_CODE_CHOOSE_OTHER_SEND:
            case REQUEST_CODE_CHOOSE_NEW_ADD_SEND:
                WechatContactBean result = (WechatContactBean) data.getSerializableExtra("result");
                if (result != null) {
                    mTvType.setText(result.getName());
                    PicLoadUtils.setupRoundPicIntoImageView(result.getAvatarSrc(), result.getAvatar(), mIvType);
                    mTradeHistoryEntity.setIconUrl(result.getAvatar());
                    mTradeHistoryEntity.setIconSourceType(result.getAvatarSrc());
                    mTradeHistoryEntity.setContent(result.getName());
                }
                break;
            case REQUEST_CODE_BANK_CARD:
                BankCardBean bankCardBean = (BankCardBean) data.getSerializableExtra("result");
                if (bankCardBean != null) {
                    String content = bankCardBean.getBankName() + "(" + bankCardBean.getBankNumber() + ")";
                    mTvType.setText(content);
                    Picasso.get().load(bankCardBean.getAvatar()).error(R.drawable.default_image).into(mIvType);
                    mTradeHistoryEntity.setContent(content);
                }
                break;
        }
    }
}
